<?php

// 后台管理系统模块
// index 模块公共函数文件

/**
 * 图片初始化
 */
function imgInit($img)
{
	$dirpath     = 'images/init/' . date('Ymd');
	$extension   = pathinfo($img, PATHINFO_EXTENSION);
	$filename    = md5(microtime(true) . mt_rand(1, 1e9)) . '.' . $extension;
	$storagePath = ATTACHMENT_ROOT . $dirpath . '/' . $filename;
	if ( !file_exists(dirname($storagePath)) ) mkdir(dirname($storagePath), 0777, true);
	$res = copy(app()->getRootPath() . '/public/init/' . $img, $storagePath);
	return $res ? ($dirpath . '/' . $filename) : '';
}

/**
 * 生成路由
 * u('index')
 * u('index/login')
 * u('index/login', ['id' => 1, 'name' => '张三']) 传参
 */
function u(...$param)
{
	// 微擎相关参数
	$weParam = \think\facade\Request::only(['c', 'a', 'eid', 'version_id'], 'get');
	// 当前控制器、方法
	$controller = request()->controller();
	$action     = request()->action();
	$route = explode('/', $param[0]);
	switch (count($route)) {
		case 1:
			$path = [
				'contro' => $controller,
				'action' => $route[0],
			];
			break;
		case 2:
			$path = [
				'contro' => $route[0],
				'action' => $route[1],
			];
			break;
	}
	// 驼峰命名转为下划线分隔命名
	$path['contro'] = strtolower(preg_replace('/(?<=[a-z])([A-Z])/', '_$1', $path['contro']));
	$final = array_merge($weParam, $path);
	// 第二个参数 请求参数
	if ( ! empty($param[1]) ) $final = array_merge($final, $param[1]);
	// 参数转为查询字符串
	$link = '';
	foreach ($final as $key => $value) {
		$link .= $key . '=' . $value . '&';
	}
	$link = rtrim($link, '&');
	// 微擎路由地址
	return request()->baseFile() . '?' . $link;
}
